package cc.comac.mom.datahandlers.entity;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cc.comac.mom.bean.EquipPatrolCheckWorkOrderItem;
import cc.comac.mom.bean.EquipPatrolCheckWorkOrderItemBean;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.dao.entity.EquipPatrolCheckWorkOrderDao;
import cc.comac.mom.dao.entity.EquipPatrolCheckWorkOrderItemDao;
import cc.comac.mom.entity.EquipPatrolCheckWorkOrderEntity;
import cc.comac.mom.entity.EquipPatrolCheckWorkOrderItemEntity;
import cc.comac.mom.redis.IdFactory;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.MomConstants;
import cc.comac.mom.util.ResultBean;
import cc.comac.mom.util.TimeUtil;

@Component
@Transactional
public class EquipPatrolCheckWorkOrderItemDataHandler extends ServiceImpl<EquipPatrolCheckWorkOrderItemDao, EquipPatrolCheckWorkOrderItemEntity>{
	@Autowired
	private EquipPatrolCheckWorkOrderItemDao equipPatrolCheckWorkOrderItemDao;
	@Autowired 
	private EquipPatrolCheckWorkOrderDao equipPatrolCheckWorkOrderDao;
	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;
	
	@Autowired
	private IdFactory idFactory;
	public ResultBean insertBatch(List<EquipPatrolCheckWorkOrderItem> list) {
		ResultBean resultBean = new ResultBean(true);
		if(list ==null || list.size()<1) {
			throw new RuntimeException("数据为空");
		}
		ArrayList<EquipPatrolCheckWorkOrderItemEntity> listEntity = new ArrayList<EquipPatrolCheckWorkOrderItemEntity>();
		for(EquipPatrolCheckWorkOrderItem item :list) {
			EquipPatrolCheckWorkOrderItemEntity innerData = item.getInnerData();
			if(innerData == null) {
				throw new RuntimeException("数据为空");
			}
			innerData.setStatus(MomConstants.EQUIP_PATROL_CHECK_ORDER_ITEM_STATUS_NOEXECUTE);
//			baseEntityDataUtil.setBaseEntityData(innerData);
			if (StringUtils.isNotEmpty(innerData.getCreator())) {
				innerData.setId(idFactory.generateId());
				//	entity.setSiteId(idUtil.getSiteId());
				innerData.setCreationTime(TimeUtil.getLocalDateTime());
				innerData.setCreationTimeZone(TimeUtil.getLocalTimeZone());
				innerData.setLastModifiedTime(TimeUtil.getLocalDateTime());
				innerData.setLastModifiedTimeZone(TimeUtil.getLocalTimeZone());
				innerData.setRowStatus(1);
			} else {
				baseEntityDataUtil.setBaseEntityData(innerData);
			}
			listEntity.add(innerData);
		}
		boolean saveBatch = this.saveBatch(listEntity);
		if(!saveBatch) {
			throw new RuntimeException("保存巡检工单项信息失败");
		}
		return resultBean;
	}
	//批量删除
	public ResultBean deleteBatch(List<Long> ids) {
		ResultBean resultBean = new ResultBean(true);
		if (ids == null || ids.size() < 1) {
			throw new RuntimeException("数据为空");
		}
		List<EquipPatrolCheckWorkOrderItemEntity> selectBatchIds = equipPatrolCheckWorkOrderItemDao.selectBatchIds(ids);
		if (selectBatchIds == null || selectBatchIds.size() < 1) {
			throw new RuntimeException("数据为空");
		}
		for (EquipPatrolCheckWorkOrderItemEntity item : selectBatchIds) {
			if (item.getStatus() == MomConstants.EQUIP_PATROL_CHECK_ORDER_ITEM_STATUS_EXECUTED) {
				resultBean.setErrorMessge("该工单项已执行，不可删除");
				return resultBean;
			}
			baseEntityDataUtil.deleteBaseEntityData(item);
		}
		boolean updateBatchById = this.updateBatchById(selectBatchIds);
		if (!updateBatchById) {
			throw new RuntimeException("批量删除定检计划工单失败");
		}
		return resultBean;
	}
	
	//工单子项执行
	public ResultBean planExecute(EquipPatrolCheckWorkOrderItem obj) {
		ResultBean resultBean = new ResultBean(true);
		if(obj == null || obj.getInnerData() == null) {
			throw new RuntimeException("数据为空");
		}
		EquipPatrolCheckWorkOrderItemEntity innerData = obj.getInnerData();
		EquipPatrolCheckWorkOrderItemEntity selectById = equipPatrolCheckWorkOrderItemDao.selectById(innerData.getId());
		if(selectById == null) {
			throw new RuntimeException("执行信息不存在");
		}
		//获取巡检工单信息
		EquipPatrolCheckWorkOrderEntity checkWorkOrderEntity = equipPatrolCheckWorkOrderDao.selectById(selectById.getPatrolCheckOrderId());
		if(checkWorkOrderEntity == null) {
			throw new RuntimeException("无法获取父级巡检工单信息");
		}
		if(checkWorkOrderEntity.getStatus() == MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_NOEXECUTE) {
			throw new RuntimeException("请先开始巡检工单执行");
		}
		baseEntityDataUtil.updateBaseEntityData(checkWorkOrderEntity);
		//判断当前状态是否为待执行
		if(selectById.getStatus() == MomConstants.EQUIP_PATROL_CHECK_ORDER_ITEM_STATUS_EXECUTED) {
			throw new RuntimeException("已执行状态不可再次执行");
		}

		innerData.setPatrolCheckDate(TimeUtil.getLocalDateTime());
		innerData.setStatus(MomConstants.EQUIP_PATROL_CHECK_ORDER_ITEM_STATUS_EXECUTED);//已执行
		baseEntityDataUtil.updateBaseEntityData(innerData);
		int updateById = equipPatrolCheckWorkOrderItemDao.updateById(innerData);
		if(updateById<1) {
			throw new RuntimeException("执行失败");
		}
		//修改计划工单的状态和执行时长
		   //计算父级工单的执行用时
		Duration duration = Duration.between(TimeUtil.fomatDateToLocalDateTime(checkWorkOrderEntity.getFirstExecuteStartDate()),TimeUtil.getLocalDateTime());
		long hours = duration.toHours();
		checkWorkOrderEntity.setActualExecuteTime(new BigDecimal(hours));
		   //判断是否为最后一条
		QueryWrapper<EquipPatrolCheckWorkOrderItemEntity> queryWrapper2 = new QueryWrapper<EquipPatrolCheckWorkOrderItemEntity>();
		queryWrapper2.eq("row_status", 1);
		queryWrapper2.eq("patrol_check_order_id",innerData.getPatrolCheckOrderId());
		queryWrapper2.notIn("patrol_check_order_item_id", innerData.getId());
		queryWrapper2.eq("status",MomConstants.EQUIP_PATROL_CHECK_ORDER_ITEM_STATUS_NOEXECUTE);
		Page<EquipPatrolCheckWorkOrderItemEntity> page2 = new Page<>(0, 1, false);
		
		IPage<EquipPatrolCheckWorkOrderItemEntity> iPage2 = equipPatrolCheckWorkOrderItemDao.selectPage(page2, queryWrapper2);
		List<EquipPatrolCheckWorkOrderItemEntity> list2 = iPage2.getRecords();
		if(list2 == null || list2.size()<1) {
			//说明为最后一条，要修改父级状态为执行完成
			checkWorkOrderEntity.setStatus(MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_EXECUTED);//执行完成
		}
		int updateById2 = equipPatrolCheckWorkOrderDao.updateById(checkWorkOrderEntity);
		if(updateById2<1) {
			throw new RuntimeException("修改巡检计划工单执行用时失败");
		}
		return resultBean;
	}
	//查询
	public ResultDev selectByFields(EquipPatrolCheckWorkOrderItemBean obj) {
		ResultDev resultDev = new ResultDev();
		if (obj.getPageSize() == 0) {
			obj.setPageSize(10);
		}
		obj.setPageNum((obj.getPageNum()-1)*obj.getPageSize());
		List<EquipPatrolCheckWorkOrderItemBean> listEquipRegularCheckPlanBean = equipPatrolCheckWorkOrderItemDao.selectByFields(obj);
		long countByFields = equipPatrolCheckWorkOrderItemDao.selectCountByFields(obj);
		
		// 将查询总数除以每页数量后向上取整获取总页数
		double pageCount = Math.ceil((double)countByFields / obj.getPageSize());
		resultDev.setEntityList(listEquipRegularCheckPlanBean);
		resultDev.setPageCount((int)pageCount);
		resultDev.setTotalQuantity((int)countByFields);
		return resultDev;
	}

	//工单子项确认
	public ResultBean confirm(List<EquipPatrolCheckWorkOrderItem> obj) {
		ResultBean resultBean = new ResultBean(true);
		if(obj == null || obj.size() == 0) {
			throw new RuntimeException("数据为空");
		}
		for(EquipPatrolCheckWorkOrderItem e:obj) {
			EquipPatrolCheckWorkOrderItemEntity innerData = e.getInnerData();
			EquipPatrolCheckWorkOrderItemEntity selectById = equipPatrolCheckWorkOrderItemDao.selectById(innerData.getId());
			if (selectById == null) {
				throw new RuntimeException("执行信息不存在");
			}
			//获取巡检工单信息
			EquipPatrolCheckWorkOrderEntity checkWorkOrderEntity = equipPatrolCheckWorkOrderDao.selectById(selectById.getPatrolCheckOrderId());
			if (checkWorkOrderEntity == null) {
				throw new RuntimeException("无法获取父级巡检工单信息");
			}
		/*if(checkWorkOrderEntity.getStatus() == MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_NOEXECUTE) {
			throw new RuntimeException("请先开始巡检工单执行");
		}*/
			baseEntityDataUtil.updateBaseEntityData(checkWorkOrderEntity);
			//判断当前状态是否为待执行
			if (selectById.getStatus() == MomConstants.EQUIP_PATROL_CHECK_ORDER_ITEM_STATUS_EXECUTED) {
				throw new RuntimeException("已巡检不能在巡检");
			}

			//innerData.setPatrolCheckDate(TimeUtil.getLocalDateTime());
			//巡检确认
			if (!StringUtils.isEmpty(innerData.getPatrolCheckUser()) && StringUtils.isEmpty(innerData.getConfirmUser())) {
				selectById.setPatrolCheckUser(innerData.getPatrolCheckUser());
				selectById.setPatrolCheckDate(innerData.getPatrolCheckDate());
				selectById.setStatus(MomConstants.EQUIP_PATROL_CHECK_ORDER_ITEM_STATUS_EXECUTEDING);//巡检确认中
			} else if (!StringUtils.isEmpty(innerData.getConfirmUser())) {
				selectById.setConfirmUser(innerData.getConfirmUser());
				selectById.setUserConfirmDate(innerData.getUserConfirmDate());
				selectById.setStatus(MomConstants.EQUIP_PATROL_CHECK_ORDER_ITEM_STATUS_EXECUTED);//已巡检
			} else {
				throw new RuntimeException("确认人不能为空");
			}
			baseEntityDataUtil.updateBaseEntityData(innerData);
			int updateById = equipPatrolCheckWorkOrderItemDao.updateById(selectById);
			if (updateById < 1) {
				throw new RuntimeException("确认失败");
			}
			//修改计划工单的状态和执行时长
			if(checkWorkOrderEntity.getFirstExecuteStartDate()==null){
				checkWorkOrderEntity.setFirstExecuteStartDate(new Date());
			}
			//计算父级工单的执行用时
			Duration duration = Duration.between(TimeUtil.fomatDateToLocalDateTime(checkWorkOrderEntity.getFirstExecuteStartDate()), TimeUtil.getLocalDateTime());
			long hours = duration.toHours();
			checkWorkOrderEntity.setActualExecuteTime(new BigDecimal(hours));
			//判断是否为最后一条
			QueryWrapper<EquipPatrolCheckWorkOrderItemEntity> queryWrapper2 = new QueryWrapper<EquipPatrolCheckWorkOrderItemEntity>();
			queryWrapper2.eq("row_status", 1);
			queryWrapper2.eq("patrol_check_order_id", selectById.getPatrolCheckOrderId());
			queryWrapper2.in("status", MomConstants.EQUIP_PATROL_CHECK_ORDER_ITEM_STATUS_NOEXECUTE, MomConstants.EQUIP_PATROL_CHECK_ORDER_ITEM_STATUS_EXECUTEDING);
			Page<EquipPatrolCheckWorkOrderItemEntity> page2 = new Page<>(0, 1, false);

			IPage<EquipPatrolCheckWorkOrderItemEntity> iPage2 = equipPatrolCheckWorkOrderItemDao.selectPage(page2, queryWrapper2);
			List<EquipPatrolCheckWorkOrderItemEntity> list2 = iPage2.getRecords();
			if (list2 == null || list2.size() < 1) {
				//说明为最后一条，要修改父级状态为执行完成
				checkWorkOrderEntity.setStatus(MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_EXECUTED);//执行完成
			}else{
				checkWorkOrderEntity.setStatus(MomConstants.EQUIP_REGULAR_CHECK_ORDER_STATUS_EXECUTEING);//执行中
			}
			int updateById2 = equipPatrolCheckWorkOrderDao.updateById(checkWorkOrderEntity);
			if (updateById2 < 1) {
				throw new RuntimeException("修改巡检计划工单执行用时失败");
			}
		}
			return resultBean;
		}

}
